package tp.pr3.instructions;





import java.util.StringTokenizer;

import tp.pr3.NavigationModule;
import tp.pr3.RobotEngine;
import tp.pr3.instructions.exceptions.InstructionExecutionException;
import tp.pr3.instructions.exceptions.WrongInstructionFormatException;
import tp.pr3.items.ItemContainer;

public class OperateInstruction
extends java.lang.Object
implements Instruction{
	
	private RobotEngine engine;
    private NavigationModule navigation;
    private ItemContainer robotContainer;
    private String itemToUse;
	
	public Instruction parse(java.lang.String cad) throws WrongInstructionFormatException
	{
		StringTokenizer instructionToken = new StringTokenizer(cad);
	    if(instructionToken.countTokens()!=2) 
			throw new WrongInstructionFormatException();
		
		String action=instructionToken.nextToken();
		if (!(action.toUpperCase().equalsIgnoreCase("OPERATE") || action.toUpperCase().equalsIgnoreCase("OPERAR")))
			throw new WrongInstructionFormatException();
		
		itemToUse=instructionToken.nextToken();
		return this;
	}
	
	public void execute() throws InstructionExecutionException
	{
		if(!robotContainer.containsItem(itemToUse))
			throw new InstructionExecutionException("WALL·E says: I have problems using the object "+itemToUse + "\n");
		
			if(!(robotContainer.getItem(itemToUse).use(engine, navigation)))
				throw new InstructionExecutionException("WALL·E says: I have problems using the object "+itemToUse+"\n");;
			try
			{
			if(!robotContainer.getItem(itemToUse).canBeUsed())
			  {
				robotContainer.useItem(robotContainer.getItem(itemToUse));
			     System.out.println("WALL·E: What a pity! I have no more " +
 				   itemToUse+
 				   " in my inventory"); 
			  }   
			}catch(Exception e){
				throw new InstructionExecutionException(e.getMessage());
			}
	}
	
	public java.lang.String getHelp()
	{
		return ("OPERATE | OPERAR <ID>");
	}
	
	
	public void configureContext(RobotEngine engine,
            NavigationModule navigation,
            ItemContainer robotContainer)
	{
	 	this.engine=engine;
	 	this.navigation=navigation;
	 	this.robotContainer=robotContainer;
	}       

}
